import { Schema, default as mongoose } from 'mongoose';
import { PermissionsSchemaObject, defaultUserPermissions } from '../perms';
export {
  PermissionsSchemaObject,
  defaultUserPermissions,
  UserPermission as UserPermissions,
} from '../perms';

export const UserSchema = new Schema({
  userId: { type: String, index: true },
  userName: { type: String },
  permissions: PermissionsSchemaObject,
  groups: { type: [String], required: true },
});
// function declared like this as a result of `this` keyword :/
UserSchema.pre('save', function (next, opts) {
  const t = this;
  t.permissions = t.permissions ?? {};
  Object.entries(defaultUserPermissions).forEach(
    ([k, v]) =>
      (t.permissions![k as keyof typeof t.permissions] =
        t.permissions![k as keyof typeof t.permissions] ?? v),
  );
  t.groups = t.groups ?? [];
  if (!t.groups.includes('Everyone')) t.groups.push('Everyone');
  next();
});
export const UserModel = mongoose.model('User', UserSchema);
export default UserModel;
